package com.supervision.parent.ui.home;

import androidx.lifecycle.ViewModelProviders;

import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.interfaces.IText;
import com.supervision.parent.R;
import com.supervision.parent.util.SaveNum;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ScheduleFragment extends Fragment {

    public static ScheduleFragment newInstance() {
        return new ScheduleFragment();
    }

    private ScheduleViewModel mViewModel;

    private String phone, webIp;

    LinearLayout llSch;
    LinearLayout llSchStu;
    List<JSONObject> jsonObjects = null;
    List<String> student = null;
    List<String> name = null;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.schedule_fragment, container, true);
        Map<String, String> userInfo = SaveNum.getUserInfo(getContext());
        if (userInfo != null) {
            phone = userInfo.get("phone");
            webIp = userInfo.get("webIp");
        }

        llSch = root.findViewById(R.id.ll_schedule);
        llSchStu = root.findViewById(R.id.ll_schedule_stu);
        llSchStu.removeAllViews();
        llSchStu.removeAllViews();
        GetScheduleAT getScheduleAT = new GetScheduleAT();
        getScheduleAT.execute(webIp, phone);
        return inflater.inflate(R.layout.schedule_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(ScheduleViewModel.class);

        // TODO: Use the ViewModel
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        llSch.removeAllViews();
    }

    class GetScheduleAT extends AsyncTask<String, String, String> implements View.OnClickListener {

        @Override
        protected String doInBackground(String... strings) {
            OkHttpClient okHttpClient = new OkHttpClient();//创建单例
            URL url;
            Request request;//创建请求
            String result = null;
            try {
                //设置url
                url = new URL("http://" + strings[0] + ":8080/getStudent/" + strings[1]);
                //设置请求
                request = new Request.Builder()
                        .url(url)
                        .build();
                //执行请求
                Response response = okHttpClient.newCall(request).execute();

                result = response.body().string();
                onProgressUpdate(result);
            } catch (Exception e) {
            }
            try {
                //设置url
                url = new URL("http://" + strings[0] + ":8080/schedule/" + strings[1]);
                //设置请求
                request = new Request.Builder()
                        .url(url)
                        .build();
                //执行请求
                Response response = okHttpClient.newCall(request).execute();

                result = response.body().string();
            } catch (Exception e) {
            }
            return result;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            JSONArray jsonArray = null;
            student = new ArrayList<>();
            name = new ArrayList<>();

            try {
                jsonArray = new JSONArray(values[0]);
            } catch (JSONException e) {
            }
            JSONObject jsonObject = null;
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    jsonObject = new JSONObject(jsonArray.get(i).toString());
                    student.add(jsonObject.optString("clazz"));
                    name.add(jsonObject.optString("name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            jsonObjects = new ArrayList<>();
            JSONArray jsonArray = null;
            try {
                jsonArray = new JSONArray(s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject jsonObject = null;
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    jsonObject = new JSONObject(jsonArray.get(i).toString());
                    jsonObjects.add(jsonObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            for (String str : student) {
                Button button = new Button(getContext());
                button.setText(name.get(student.indexOf(str)));
                button.setId(student.indexOf(str));
                button.setOnClickListener(this);
                llSchStu.addView(button);
            }

        }

        @Override
        public void onClick(View v) {
            llSch.removeAllViews();
            String[] Week = {"Mon", "Tue", "Wed", "Thu", "Fri"};
            String[] number = {"一", "二", "三", "四", "五"};
            String course;
            JSONObject jsonObject = jsonObjects.get(v.getId());
            if (jsonObject != null) {
                LinearLayout num = new LinearLayout(getActivity());
                num.setOrientation(LinearLayout.VERTICAL);
                for (int i = 0; i < 6; i++) {
                    TextView tvNum = new TextView(getActivity());
                    if (i == 0) {
                        tvNum.setText("\n\n");
                    } else if (i == 1) {
                        tvNum.setText(" 上  " + number[i - 1] + " \n 午       \n");
                    } else if (i == 4) {
                        tvNum.setText(" 下  " + number[i - 1] + " \n 午       \n");
                    } else {
                        tvNum.setText("       " + number[i - 1] + "        \n\n");
                    }
                    num.addView(tvNum);
                }
                llSch.addView(num);

                for (int i = 0; i < 5; i++) {
                    LinearLayout linearLayout = new LinearLayout(getActivity());
                    linearLayout.setOrientation(LinearLayout.VERTICAL);
                    TextView tvWeek = new TextView(getActivity());
                    tvWeek.setText("周" + "        \n" + number[i] + "\n——");
                    linearLayout.addView(tvWeek);
                    for (int j = 1; j < 6; j++) {
                        course = jsonObject.optString(Week[i] + j);
                        TextView textView = new TextView(getActivity());
                        textView.setText(course.charAt(0) + "  \n" + course.charAt(1) + "  \n——");
                        linearLayout.addView(textView);
                    }
                    llSch.addView(linearLayout);
                }
            }
        }


    }
}


